const langPath = '/tesseract.js-offline-master/lang-data'; // 指向包含中文语言包的目录
let worker = null;  //OCR相关
var sheData = [];
var maiData = [];
var jianchaData = [];
var yaoData = [];
var bookData;
var zhenghouData,optionsZhenghou;
var zhongyiZhengzhuangData,optionsZhongyi;
var zhongyaoData;
var cankao = [];
var yianId = document.getElementById('yianId');
var shenhe = document.getElementById('shenhe');
var bookName = document.getElementById('shuming');
var bookAuthor = document.getElementById('zuozhe');
var bookPublisher = document.getElementById('chubanshe');
var bookEdition = document.getElementById('banci');
var bookEditionTime = document.getElementById('chubanshijian');
var bookISBN = document.getElementById('isbn');
var xiyiXiangmu = document.getElementById('jianchaxiangmu');
var xiyiShijian = document.getElementById('shijian');
var xiyiJieguo = document.getElementById('jieguo');
var xiyiTupian = document.getElementById('jianchafile');
var xiyiJcShow = document.getElementById('divJiancha');
var xiyiBingming = document.getElementById('xiyiBingming');
var xyBmshowAdd = document.getElementById('xyBmshowAdd');
var jianban = document.getElementById('jianban');
var xiangban = document.getElementById('xiangban');
var chufangming_J = document.getElementById('jianCfmc');
var zhongyaoming_J = document.getElementById('jianYaoming');
var yaoliang_J = document.getElementById('yaoliang_jd');
var beizhu_J = document.getElementById('beizhu_jd');
var zongyaowei_J = document.getElementById('chufangdivjiandan');
var jishu_J = document.getElementById('jishu_jb');
var jianfufa_J = document.getElementById('jianfufa_jb');
var zhongyaoShow_J = document.getElementById('zhongyaoShow_J');
var chufangming_X = document.getElementById('chufangmingcheng');
var leixing_X = document.getElementById('leixing');
var jixing_X = document.getElementById('jixing');
var jianfufa_X = document.getElementById('jianfufa');
var fuyaoshijian_X = document.getElementById('fuyaoshijian');
var jishu_X = document.getElementById('jishu');
var shiyongfangfa_X =document.getElementById('shiyongfangfa');
var cishuyaoliang_X = document.getElementById('cishuyaoliang');
var fuhoufankui_X = document.getElementById('fuhoufankui');
var qitashixiang_X =document.getElementById('qitashixiang');
var zhongyaoming_X =document.getElementById('zhongyaoming');
var yaoliang_X = document.getElementById('yaoliang');
var jinguzhiJin_X = document.getElementById('jinzhi');
var jinguzhiGu_X = document.getElementById('guzhi');
var daiding_X =document.getElementById('daiding');
var paozhi_X = document.getElementById('paozhi');
var chandi_X =document.getElementById('chandi');
var beizhu_X = document.getElementById('beizhu');
var zhongyaoShow_X = document.getElementById('zhongyaoShow_X');
var nian = document.getElementById('year');
var yue = document.getElementById('month');
var ri = document.getElementById('day');
var otherTime = document.getElementById('otherTime');
var yianBianhao = document.getElementById('biaohao');
var jingyanfangXishu = document.getElementById('ExperienceCoefficient');
var fengmian = document.getElementById('smallfile4');
var banquanye = document.getElementById('smallfile5');
var huanzheXingming = document.getElementById('xingming');
var jiezhenYisheng = document.getElementById('jiuzhenyisheng');
var chufuzhen = document.getElementById('jiuzhenleixin');
var keshi = document.getElementById('keshi');
var xingbie = document.getElementById('xingbie');
var hunkuang = document.getElementById('hunkuang');
var yaowuguominshi = document.getElementById('yaowoguominshi');
var nianling = document.getElementById('nianling');
var fabingJieqi = document.getElementById('fabingjieqi');
var chaodai = document.getElementById('chaodai');
var qishiye = document.getElementById('yema');
var zhongzhiye = document.getElementById('yemaEnd');
var zhusu = document.getElementById('zhushu');
var xianbingshi = document.getElementById('xianbingshi');
var FangFaoyuanwen = document.getElementById('FangFaoyuanwen');
var jiazushi = document.getElementById('jiazushi');
var jiwangshi = document.getElementById('jiwangshi');
var shemaiZongtiqingkuang = document.getElementById('shezhen');
//舌再定  脉再定  td
var shiyanshiJiancha = document.getElementById('sysjc');
var score = document.getElementById('startP');
//20条再定 done
var hanre = document.getElementById('select1');
var hanzheng = document.getElementById('select2');
var xingti = document.getElementById('select3');
var shenzhi =document.getElementById('select4');
var yinshi =document.getElementById('select5');
var yinshui =document.getElementById('select6');
var xiaobian =document.getElementById('select7');
var dabian = document.getElementById('select8');
var shuimian =document.getElementById('select9');
var yuyin = document.getElementById('select10');
var toumian =document.getElementById('select11');
var toubu = document.getElementById('select12');
var ermu = document.getElementById('select13');
var koubiyan =document.getElementById('select14');
var jingxiang = document.getElementById('select15');
var xiongfu = document.getElementById('select16');
var  yaobei = document.getElementById('select17');
var sizhi = document.getElementById('select18');
var yuejing = document.getElementById('select19');
var baidai = document.getElementById('select20');
var zhenghou = document.getElementById('select21');
var bingji = document.getElementById('select22');
var inputZhenghou = document.getElementById('shoudongZhenghou');
var inputBingji = document.getElementById('zyzd');
//症候再定  病机再定 zd  西医检查数据再定 zd
var xiyiZhenduan = document.getElementById('xyBmshowAdd');
var zhize = document.getElementById('zhize');
var zhifa = document.getElementById('zhifa');
var shuoming = document.getElementById('shuoming');
var qitaYizhu = document.getElementById('qtyz');
var yaohoufankui = document.getElementById('bafx');
var yaodian = document.getElementById('xxxd');
var jcTupian = [];
getData('/book/',1);
getData('/wxya/zhenghou',2);
getData('/wxya/zhongyiZhengzhuang',3);
getData('/zyxx/',4);
//OCR识别函数，异步
async function OCR() {
    var ocrImg = document.getElementById('fileInput').files[0];
    var ocrShow = document.getElementById('resultMsg');
    var imagePreView = document.getElementById('imgPreview');
    if (!ocrImg) {
        alert('请选择要识别的图片！');
        return;
    }
    var imgUrl = window.URL.createObjectURL(ocrImg);
    imagePreView.setAttribute("src", imgUrl);
    // 更改img url 以后释放 url
    imagePreView.onload = function () {
        console.log('图片加载成功');
        URL.revokeObjectURL(imgUrl)//安全性，释放URL
    };
    const requestBody = new FormData();
    requestBody.append('img',ocrImg);
    fetch('/wxya/ocr',
        {
            method: 'POST',
            body: requestBody
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求错误');
            }
            return response.text(); // 将响应数据解析为文本
        })
        .then(data => {
            // 在页面上显示后端返回的字符串
            ocrShow.textContent = data;
        })
        .catch(error => {
            alert("识别次数已达到上限！");
            console.error('发生错误:', error);
        });



}
//复制到剪切板函数
async function copyToClipboard() {
    const textToCopy = document.getElementById('resultMsg').value;
    try {
        await navigator.clipboard.writeText(textToCopy);
    } catch (err) {
        console.error('复制到剪贴板失败：', err);
        alert('复制到剪贴板失败，请手动复制文本：' + textToCopy);
    }
}

function ocrPreview(){
    var ocrImg = document.getElementById('fileInput').files[0];
    var imagePreView = document.getElementById('imgPreview');
    if (!ocrImg) {
        return;
    }
    var imgUrl = window.URL.createObjectURL(ocrImg);
    imagePreView.setAttribute("src", imgUrl);
    // 更改img url 以后释放 url
    imagePreView.onload = function () {
        URL.revokeObjectURL(imgUrl)//安全性，释放URL
    };
}
function previewImageCover() {
    var preview = document.getElementById('img4');
    var fileDom = document.getElementById('smallfile4');
    // 获取得到file 对象
    var file = fileDom.files[0]
    // 限制上传图片的大小
    if (file.size > 1024 * 1024 * 5) {
        alert('图片大小不能超过 5MB!');
        return false;
    }
    // 创建url
    var imgUrl = window.URL.createObjectURL(file)
    preview.setAttribute("src", imgUrl)
    // 更改img url 以后释放 url
    preview.onload = function () {
        URL.revokeObjectURL(imgUrl)//安全性，释放URL
    }
}
function previewImageRight() {
    var preview = document.getElementById('img5');
    var fileDom = document.getElementById('smallfile5');
    // 获取得到file 对象
    var file = fileDom.files[0]
    // 限制上传图片的大小
    if (file.size > 1024 * 1024 * 5) {
        alert('图片大小不能超过 5MB!');
        return false;
    }
    // 创建url
    var imgUrl = window.URL.createObjectURL(file)
    preview.setAttribute("src", imgUrl)
    // 更改img url 以后释放 url
    preview.onload = function () {
        URL.revokeObjectURL(imgUrl)//安全性，释放URL
    }
}
function getData(url,somedata) {
    fetch(url)
        .then(response => response.json())
        .then(data => {
            data.forEach(obj => {
                for (let key in obj) {
                    if (obj.hasOwnProperty(key) && obj[key] === null) {
                        obj[key] = ''; // 将属性值为 null 的属性替换为空字符串
                    }
                }
            });
            switch (somedata){
                case 1:bookData = data;
                    break;
                case 2:zhenghouData = data;
                    optionsZhenghou = zhenghouData.map(item => item.zhenghou);
                    break;
                case 3:zhongyiZhengzhuangData = data;
                    optionsZhongyi = zhongyiZhengzhuangData.map(item => item.mingcheng);
                    initialize();
                    break;
                case 4:
                    zhongyaoData=data;
                    break;
            }
            //  console.log(data);
            // somedata = data; // 将返回的数据赋值给全局变量
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}
function searchData() {
    var keyword = bookName.value.trim().toUpperCase();
    var results = document.getElementById('searchResults');
    // 清空之前的查询结果
    results.style.display = 'block';
    results.innerHTML = '';
    // 遍历JSON数据，查找匹配的信息
    for (var i = 0; i < bookData.length; i++) {
        var book = bookData[i];
        var nameIndex = book.name;
        if (nameIndex == null)
            continue;
        var name = nameIndex.toUpperCase();
        if (name.includes(keyword)) {
            // 创建li元素，并将匹配的信息添加到ul标签中
            var li = document.createElement('li');
            li.textContent = nameIndex;
            // 添加自定义属性保存对应的bookData对象
            li.bookData = book;
            // 添加click事件监听器
            li.addEventListener('click', function () {
                var nothing = '';
                // 点击查询结果时，将信息装配到input标签中
                bookName.value = this.bookData.name;
                bookAuthor.value = this.bookData.author;
                bookPublisher.value = this.bookData.publisher;
                bookEdition.value = this.bookData.edition;
                bookEditionTime.value = this.bookData.editionTime;
                bookISBN.value = this.bookData.isbn;
                // 将查询结果隐藏
                results.style.display = 'none';
            });
            results.appendChild(li);
        }
    }
    document.addEventListener('click', function (event) {
        const targetElement = event.target;

        // 检查点击事件的目标元素是否位于searchResults或其子元素内，以及是否位于输入框内
        const clickedInsideSearchResults = targetElement === results || results.contains(targetElement);
        const clickedInsideSearchInput = targetElement === bookName;

        // 如果不是点击在searchResults或输入框内，隐藏searchResults
        if (!clickedInsideSearchResults && !clickedInsideSearchInput) {
            results.style.display = 'none';
        }
    });
}
function searchZhongyao() {
    var keyword = zhongyaoming_J.value.trim().toUpperCase();
    var results = document.getElementById('zhongyaoSearchResults');
    // 清空之前的查询结果
    results.style.display = 'block';
    results.innerHTML = '';
    // 遍历JSON数据，查找匹配的信息
    for (var i = 0; i < zhongyaoData.length; i++) {
        var zhongyao = zhongyaoData[i];
        var nameIndex = zhongyao.yaoming;
        if (nameIndex == null)
            continue;
        var name = nameIndex.toUpperCase();
        if (name.includes(keyword)) {
            // 创建li元素，并将匹配的信息添加到ul标签中
            var li = document.createElement('li');
            li.textContent = nameIndex;
            // 添加自定义属性保存对应的bookData对象
            li.zhongyaoData = zhongyao;
            // 添加click事件监听器
            li.addEventListener('click', function () {
                // 点击查询结果时，将信息装配到input标签中
                zhongyaoming_J.value = this.zhongyaoData.yaoming;
                // 将查询结果隐藏
                results.style.display = 'none';
            });
            results.appendChild(li);
        }
    }
    document.addEventListener('click', function (event) {
        const targetElement = event.target;

        // 检查点击事件的目标元素是否位于searchResults或其子元素内，以及是否位于输入框内
        const clickedInsideSearchResults = targetElement === results || results.contains(targetElement);
        const clickedInsideSearchInput = targetElement === zhongyaoming_J;

        // 如果不是点击在searchResults或输入框内，隐藏searchResults
        if (!clickedInsideSearchResults && !clickedInsideSearchInput) {
            results.style.display = 'none';
        }
    });
}
function searchZhongyao_X() {
    var keyword = zhongyaoming_X.value.trim().toUpperCase();
    var results = document.getElementById('zhongyaoSearchResults_X');
    // 清空之前的查询结果
    results.style.display = 'block';
    results.innerHTML = '';
    // 遍历JSON数据，查找匹配的信息
    for (var i = 0; i < zhongyaoData.length; i++) {
        var zhongyao = zhongyaoData[i];
        var nameIndex = zhongyao.yaoming;
        if (nameIndex == null)
            continue;
        var name = nameIndex.toUpperCase();
        if (name.includes(keyword)) {
            // 创建li元素，并将匹配的信息添加到ul标签中
            var li = document.createElement('li');
            li.textContent = nameIndex;
            // 添加自定义属性保存对应的bookData对象
            li.zhongyaoData = zhongyao;
            // 添加click事件监听器
            li.addEventListener('click', function () {
                // 点击查询结果时，将信息装配到input标签中
                zhongyaoming_X.value = this.zhongyaoData.yaoming;
                // 将查询结果隐藏
                results.style.display = 'none';
            });
            results.appendChild(li);
        }
    }
    document.addEventListener('click', function (event) {
        const targetElement = event.target;

        // 检查点击事件的目标元素是否位于searchResults或其子元素内，以及是否位于输入框内
        const clickedInsideSearchResults = targetElement === results || results.contains(targetElement);
        const clickedInsideSearchInput = targetElement === zhongyaoming_X;

        // 如果不是点击在searchResults或输入框内，隐藏searchResults
        if (!clickedInsideSearchResults && !clickedInsideSearchInput) {
            results.style.display = 'none';
        }
    });
}
function showxiyibiao(){
    document.getElementById('xiyijianchabiao').style.display='block';
    document.getElementById('jianShiyan').style.display='none';
}
function showNoXiyi(){
    document.getElementById('xiyijianchabiao').style.display='none';
    document.getElementById('jianShiyan').style.display='block';
}
//添加西医检查数据的表格
function addXiyiJc(){
    let xiangmu = xiyiXiangmu.value;
    if(xiangmu==""){
        alert("请选择检查项目！");
        return;
    }
    let shijian = xiyiShijian.value;
    let jieguo = xiyiJieguo.value;
    let tupian = xiyiTupian.files[0];
    const newRow = xiyiJcShow.insertRow();
    // 创建并填充每个单元格
    const cell1 = newRow.insertCell();
    cell1.textContent = (xiyiJcShow.rows.length - 1).toString();
    const cell2 = newRow.insertCell();
    cell2.textContent = xiangmu;
    const cell3 = newRow.insertCell();
    cell3.textContent = shijian;
    const cell4 = newRow.insertCell();
    cell4.classList.add('xiyiCell');
    cell4.textContent = jieguo;
    const cell5 = newRow.insertCell();
    cell5.classList.add('xiyiCell');
    if(tupian!=null)
        cell5.textContent = tupian.name;
    const cell6 = newRow.insertCell();
    var deleteLink = document.createElement("a");
    deleteLink.href = "#";
    deleteLink.textContent = "删除";
    deleteLink.onclick = function () {
        deleteRow(this);
    };
    cell6.appendChild(deleteLink);
    jcTupian.push(tupian !== null ? tupian : null);
    xiyiXiangmu.value="请选择";
    xiyiShijian.value='';
    xiyiJieguo.value='';
    xiyiTupian.value='';
}
// 西医检查数据表格的删除函数
function deleteRow(link) {
    var row = link.parentNode.parentNode;
    event.preventDefault(); // 阻止默认链接点击行为
    row.parentNode.removeChild(row);
}
//西医诊断的检测回车添加数据
function addEnter(event){
    // 检查按下的按键是否为回车键，回车键的keyCode是13
    if (event.keyCode === 13) {
        addXyZhenduan();
    }
}
//西医诊断添加内容
function addXyZhenduan(){
    var value = xiyiBingming.value+",";
    if(value==",")
        return;
    xiyiBingming.value="";
    xyBmshowAdd.innerText=xyBmshowAdd.innerText + value;
}
//清空上面的内容
function clearXyZhenduanShow(){
    xyBmshowAdd.innerText="";
}
function showJianban(){
    jianban.style.display='block';
    xiangban.style.display='none';
}
function showXiangban(){
    jianban.style.display='none';
    xiangban.style.display='block';
}
function batchload_J() {
    const file = document.getElementById('fileupload_J').files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            outputColumns_J(rows);
        };
        reader.readAsArrayBuffer(file);
    }
}

function outputColumns_J(rows) {
    for (let i = 1; i < rows.length; i++) { // 跳过第一行
        const rowData = rows[i];
        let zhongyao = rowData[0],yaoliang = rowData[1],beizhu = rowData[2];
        if (yaoliang == undefined) {
            yaoliang = '';
        }else{
            const lastChar = yaoliang.charAt(yaoliang.length - 1);
            if (!isNaN(parseInt(lastChar))) {
                yaoliang+='克';
            }
        }
        if(beizhu==undefined){
            beizhu='';
        }
        var sort = 0;
        if (data_J.length > 0) {
            sort = data_J[data_J.length - 1].sort+1;
        }
        data_J[cnt_J]={
            zhongyao:zhongyao,
            yaoliang:yaoliang,
            beizhu:beizhu,
            paozhi:null,
            chandi:null,
            daiding:null,
            sort:sort
        }
        cnt_J++;
    }
    addCf_J_Show();
}
function batchload_X() {
    const file = document.getElementById('fileupload_X').files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            outputColumns_X(rows);
        };
        reader.readAsArrayBuffer(file);
    }
}

function outputColumns_X(rows) {
    for (let i = 1; i < rows.length; i++) { // 跳过第一行
        const rowData = rows[i];
        let zhongyao = rowData[0], yaoliang = rowData[1], daiding = rowData[2], paozhi = rowData[3], chandi = rowData[4],
            beizhu = rowData[5];
        if (yaoliang == undefined) {
            yaoliang = '';
        }else{
            const lastChar = yaoliang.charAt(yaoliang.length - 1);
            if (!isNaN(parseInt(lastChar))) {
                yaoliang+='克';
            }
        }
        if (beizhu == undefined) {
            beizhu = '';
        }
        if (daiding == undefined) {
            daiding = '';
        }
        if (paozhi == undefined) {
            paozhi = '';
        }
        if (chandi == undefined) {
            chandi = '';
        }
        var sort = 0;
        if (data_X.length > 0) {
            sort = data_X[data_X.length - 1].sort + 1;
        }
        data_X[cnt_X] = {
            zhongyao: zhongyao,
            yaoliang: yaoliang,
            daiding: daiding,
            paozhi: paozhi,
            chandi: chandi,
            beizhu: beizhu,
            sort: sort
        }
        cnt_X++;
    }
    addCf_X_Show();
}
let cnt_J=0,cnt_X=0;
var data_J=[],data_X=[];
var spnumber_jd = document.getElementById('spnumber_jd');
var spnumber_X = document.getElementById('spnumber_X');
function addCf_J(){
    let zhongyao = zhongyaoming_J.value;
    if(zhongyao==""){
        alert("请输入中药名！");
        return;
    }
    let yaoliang = yaoliang_J.value;
    let beizhu = beizhu_J.value;
    zhongyaoming_J.value='';
    yaoliang_J.value='';
    beizhu_J.value='';
    if (yaoliang == undefined) {
        yaoliang = '';
    }else{
        const lastChar = yaoliang.charAt(yaoliang.length - 1);
        if (!isNaN(parseInt(lastChar))) {
            yaoliang+='克';
        }
    }
    var exist = false;
    if (!exist) {
        var sort = 0;
        if (data_J.length > 0) {
            sort = data_J[data_J.length - 1].sort+1;
        }
        data_J[cnt_J]={
            zhongyao:zhongyao,
            yaoliang:yaoliang,
            beizhu:beizhu,
            paozhi:null,
            chandi:null,
            daiding:null,
            sort:sort
        }
    }
    cnt_J++;
    addCf_J_Show();
}
addCf_J_Show();
function addCf_J_Show(){
    var container = document.getElementById('zhongyaoShow_J');
    if (data_J.length!=0) {
        var html = "";
        for(var j=0;j<data_J.length;j++){
            for(var k=0;k+1<data_J.length-j;k++){
                if(data_J[k].sort>data_J[k+1].sort){
                    var t=data_J[k];
                    data_J[k]=data_J[k+1];
                    data_J[k+1]=t;
                }
            }
        }
        for (var i = 0; i < data_J.length; i++) {
            var item = data_J[i];
            html += '<span class="fangjispan">' + item.zhongyao + ' &nbsp; ' + item.yaoliang + ' &nbsp; ' + item.beizhu + ' &nbsp; ' + ' <img src="/images/quxiao.png" alt="" class="quxiaopic" onclick="del_J(\'' +i + '\')">';
            if (i != 0) {
                html += '<img src="/images/up.png" class="quxiaopic" onclick="up_J(\'' + i + '\')"><img>';
            }
            if (i != data_J.length-1) {
                html += '<img src="/images/down.png" class="quxiaopic" onclick="down_J(\'' + i + '\')"><img>';
            }
            html += '</span>';
        }
        spnumber_jd.innerHTML = data_J.length;
        // 清空容器
        container.innerHTML = "";
        // 添加新内容
        container.innerHTML += html;
    } else {
        spnumber_jd.innerHTML = 0;
        container.innerHTML = "";
    }
}
function del_J(p) {
    data_J.splice(p,1)
    cnt_J--;
    addCf_J_Show();
}
function up_J(i) {
    var sortp=data_J[i].sort
    data_J[i].sort=data_J[i-1].sort
    data_J[i-1].sort=sortp
    addCf_J_Show();
}
function down_J(i) {
    var sortp=data_J[i].sort
    data_J[i].sort=data_J[++i].sort
    data_J[i].sort=sortp
    addCf_J_Show();
}
function addCf_X(){
    let zhongyao = zhongyaoming_X.value;
    if(zhongyao==""){
        alert("请输入中药名");
        return;
    }
    let yaoliang = yaoliang_X.value;
    let paozhi = paozhi_X.value;
    let chandi = chandi_X.value;
    let beizhu = beizhu_X.value;
    let daiding = daiding_X.value;
    zhongyaoming_X.value='';
    yaoliang_X.value='';
    paozhi_X.value='';
    chandi_X.value='';
    beizhu_X.value='';
    daiding_X.value='待定';
    if (yaoliang == undefined) {
        yaoliang = '';
    }else{
        const lastChar = yaoliang.charAt(yaoliang.length - 1);
        if (!isNaN(parseInt(lastChar))) {
            yaoliang+='克';
        }
    }
    var exist = false;

    if (!exist) {
        var sort = 0;
        if (data_X.length > 0) {
            sort = data_X[data_X.length - 1].sort+1;
        }
        data_X[cnt_X]={
            zhongyao:zhongyao,
            yaoliang:yaoliang,
            daiding:daiding,
            paozhi:paozhi,
            chandi:chandi,
            beizhu:beizhu,
            sort:sort
        }
    }
    cnt_X++;
    addCf_X_Show();
}
function addCf_X_Show(){
    var container = document.getElementById('zhongyaoShow_X');
    if (data_X.length!=0) {
        var html = "";
        for(var j=0;j<data_X.length;j++){
            for(var k=0;k+1<data_X.length-j;k++){
                if(data_X[k].sort>data_X[k+1].sort){
                    var t=data_X[k];
                    data_X[k]=data_X[k+1];
                    data_X[k+1]=t;
                }
            }
        }
        for (var i = 0; i < data_X.length; i++) {
            var item = data_X[i];
            html += '<span class="fangjispan">' + item.zhongyao + ' &nbsp; ' + item.yaoliang + ' &nbsp; ' + item.daiding + ' &nbsp; '+ item.paozhi + ' &nbsp; '+ item.chandi + ' &nbsp; '+ item.beizhu + ' &nbsp; ' + ' <img src="/images/quxiao.png" alt="" class="quxiaopic" onclick="del_X(\'' +i + '\')">';
            if (i != 0) {
                html += '<img src="/images/up.png" class="quxiaopic" onclick="up_X(\'' + i + '\')"><img>';
            }
            if (i != data_X.length-1) {
                html += '<img src="/images/down.png" class="quxiaopic" onclick="down_X(\'' + i + '\')"><img>';
            }
            html += '</span>';
        }
        spnumber_X.innerHTML = data_X.length;
        // 清空容器
        container.innerHTML = "";
        // 添加新内容
        container.innerHTML += html;
    } else {
        spnumber_X.innerHTML = 0;
        container.innerHTML = "";
    }
}
function del_X(p) {
    data_X.splice(p,1)
    cnt_X--;
    addCf_X_Show();
}
function up_X(i) {
    var sortp=data_X[i].sort
    data_X[i].sort=data_X[i-1].sort
    data_X[i-1].sort=sortp
    addCf_X_Show();
}
function down_X(i) {
    var sortp=data_X[i].sort
    data_X[i].sort=data_X[++i].sort
    data_X[i].sort=sortp
    addCf_X_Show();
}
function saveBtn(){
    postData();

    jianchaData=[];
    jcTupian=[];
}
function ysFun(){
    let fen = score.value;
    if(fen==''){
        alert("您还没有评分！");
        return;
    }
    let shenheVal = '一审';
    var formData =new FormData();
    formData.append("id",yianId.value);
    formData.append("shenhe",shenheVal);
    formData.append("score",fen);
    fetch('/wxya/shenhe', {
        method: 'PUT',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            console.log("发送成功");
        })
        .catch(error => {
            console.log(error);
        });
    alert("审核成功！");
    window.location.href="/wxya/edit/"+yianId.value;
}
function esFun(){
    let fen = score.value;
    if(fen==''){
        alert("您还没有评分！");
        return;
    }
    let shenheVal = '通过';
    var formData =new FormData();
    formData.append("id",yianId.value);
    formData.append("shenhe",shenheVal);
    formData.append("score",fen);
    fetch('/wxya/shenhe', {
        method: 'PUT',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            console.log("发送成功");
        })
        .catch(error => {
            console.log(error);
        });
    alert("审核成功！");
    window.location.href="/wxya/edit/"+yianId.value;
}
<!--下面的script是关于那22个框-->
// 示例数据：多个数组，每个数组对应一个下拉多选框的选项
var options1 = ['不恶寒', '不发热', '潮热', '但热不寒', '低热', '恶风', '恶风寒', '恶寒', '恶寒发热', '恶热', '发热', '高热', '寒栗', '寒热往来',
    '寒战', '内热', '怕风', '怕冷', '日晡潮热', '啬啬恶寒', '身寒', '身热', '身热不扬', '身热夜甚', '身热肢寒', '手足寒', '外寒', '往来寒热', '微恶风',
    '微恶风寒', '微热', '畏寒', '畏寒发热', '畏冷', '五心烦热', '午后潮热', '淅淅恶风', '翕翕发热', '夜热早凉', '一阵恶寒，一阵发热', '一阵怕冷，一阵发热', '憎寒发热',
    '战栗', '振寒', '蒸蒸发热', '壮热'];

var options2 = ['多汗', '少汗', '半身汗出', '大汗', '但头汗出', '盗汗', '局部无汗', '局部有汗', '冷汗', '冷汗淋漓',
    '热甚汗多', '无汗','壮热无汗', '自汗', '微汗', '漐漐汗出', '汗出濈濈然'];

var options3 = ['抽搐', '拘挛', '蠕动', '颤动', '肥胖', '消瘦', '肌肉疼痛', '肌肉发胀', '肌肉酸楚', '肌肉萎缩',
    '肉松皮缓', '乏力', '倦怠', '倦怠乏力', '四肢不用', '肢体瘫痪', '半身不遂', '蜷卧缩足', '仰面伸足', '坐而仰首',
    '坐而俯首', '麻木', '发麻', '疼痛', '皮肤干燥', '皮肤黄染', '浮肿', '易感冒', '瘙痒', '项软', '龟背', '项背拘急',
    '桶状胸', '鸡胸', '四肢疼痛'];

var options4 = ['少神', '失神', '假神', '神乱', '神昏', '谵语', '有神', '急躁易怒', '多怒', '易怒', '喜怒',
    '心烦', '烦躁', '发狂', '喜静懒动', '善恐', '易惊', '闷闷不乐', '多疑善虑', '多愁善感', '抑郁', '多疑', '悲观',
    '喜叹气', '喜太息', '神情淡漠', '健忘', '喜忘', '呵欠', '见水欲尿'];

var options5 = ['食欲不振', '纳食佳', '纳佳', '纳食尚可', '纳可', '纳食一般', '食少', '不欲食', '纳差', '纳呆',
    '纳少', '吞咽困难', '呃逆', '嗳气', '泛酸', '返酸', '反酸', '嘈杂', '烧心', '消谷善饥', '多食', '嗳气酸馊',
    '嗳腐吞酸', '多食易饥', '消谷善饥', '饥不欲食', '偏食', '偏嗜异物'];

var options6 = ['口干', '口渴', '喜饮', '多饮', '不喜饮', '喜冷饮', '渴喜冷饮', '喜热饮', '渴喜热饮', '不渴',
    '口渴多饮', '口渴引饮', '口大渴', '口微渴', '渴不多饮'];

var options7 = ['小便淡黄', '小便黄赤', '尿长', '尿短', '尿少', '尿短黄', '小便不利', '小便失禁', '小便自利',
    '尿后余沥', '尿不尽', '小便淋漓', '尿急', '尿频', '尿痛', '小便灼热', '尿清', '小便浑浊', '尿血',
    '尿中砂石', '尿浮脂膏', '小便泡沫', '小便臊臭', '小便味甜', '小便清长', '尿清长', '多尿', '小便不通',
    '夜尿多', '夜尿频多'];

var options8 = ['大便尚可', '大便稀溏', '便滽', '大便溏', '大便偏稀', '大便干结', '便干', '大便干', '大便偏干',
    '溏结不调', '大便时干时稀', '经常便秘', '经常腹泻', '大便次数少', '大便次数多', '大便艰难', '大便不爽',
    '大便不畅', '大便失禁', '里急', '后重', '里急后重', '大便夹冻', '大便黏液', '便血', '大便带血', '黑便',
    '大便带虫', '大便味臭', '大便色绿', '大便色白', '大便量多', '大便量少', '大便细', '矢气', '放屁', '矢气多', '矢气少'];

var options9 = ['不寐', '嗜睡', '多梦', '恶梦', '梦交', '睡眠尚可', '眠可', '梦游', '失眠', '多梦',
    '入睡困难', '睡后易醒', '易惊醒', '遗精'];

var options10 = ['语言謇涩', '错语', '失语', '呓语', '声音高亢', '声音清脆', '声音嘶哑', '声音重浊', '语声低微', '谵语', '郑声'];

var options11 = ['头痛', '头蒙', '头胀', '头重', '头昏', '头摇', '头身酸重', '牙齿松动', '牙痛', '牙龈肿', '牙龈出血',
    '目赤', '目晴发黄', '目眩', '目昏', '目干涩', '目痛', '目痒', '雀目', '近视', '暴盲', '两目灼热', '羞明流泪', '眵多',
    '眼窝凹陷', '眼球突出', '目瞤', '眼眶发黑', '眼睑下垂', '眼睑浮肿', '口苦', '口甜', '口酸', '口中酸馊', '口淡无味', '口眼歪斜',
    '口噤', '口臭', '多涎唾', '口角流涎', '唇麻', '唇热', '唇干', '唇肿', '鼻塞', '鼻痛', '鼻痒', '流涕', '鼻干', '鼻出血',
    '喷嚏', '鼻鼾', '不闻香臭', '咽干', '咽痛', '咽痒', '喉中痰鸣', '咽如物梗', '咽红', '咽肿', '咽喉溃烂', '耳鸣', '耳胀', '耳痛',
    '耳痒', '耳聋', '重听', '耳出血'];

var options12 = ['头痛', '头蒙', '头胀', '头重', '头昏', '头摇', '头身酸重', '方头'];

var options13 = ['目赤', '目晴发黄', '目眩', '目昏', '目干涩', '目痛', '目痒', '雀目', '近视', '暴盲', '两目灼热',
    '羞明流泪', '眵多', '眼窝凹陷', '眼球突出', '目瞤', '眼眶发黑', '眼睑下垂', '眼睑浮肿', '耳鸣', '耳胀',
    '耳痛', '耳痒', '耳聋', '重听', '耳出血'];

var options14 = ['牙齿松动', '牙痛', '牙龈肿', '牙龈出血', '口苦', '口甜', '口酸', '口中酸馊', '口淡无味',
    '口眼歪斜', '口噤', '口臭', '多涎唾', '口角流涎', '唇麻', '唇热', '唇干', '唇肿', '鼻塞', '鼻痛',
    '鼻痒', '流涕', '鼻干', '鼻出血', '喷嚏', '鼻鼾', '不闻香臭', '咽干', '咽痛', '咽痒', '喉中痰鸣',
    '咽如物梗', '咽红', '咽肿', '咽喉溃烂'];

var options15 = ['颈脉动甚', '瘰疬', '项软', '颈项拘急', '项背强', '头项强痛'];

var options16 = ['恶心', '呕吐', '呕', '吐', '干呕', '哕', '咳嗽', '干咳', '呛咳', '顿咳', '呼吸急促',
    '呼吸困难', '呼吸气粗', '呼吸微弱', '气短', '上气', '少气/气微', '夺气', '胁痛', '胁胀', '胁部拘急',
    '胁部灼热', '腹痛', '腹胀', '单腹胀大', '肠鸣', '腹坠', '腹部板硬', '腹中灼热', '腹中发凉', '腹部悸动',
    '胸痛', '胸闷', '胸中灼热', '胸中发凉', '心悸', '心烦', '心悬', '乳房痛', '乳房胀', '乳头出血'];

var options17 = ['腰痛', '背痛', '腰酸', '腰胀', '腰重', '腰冷', '腰热', '龟背', '项背拘急'];

var options18 = ['足跟痛', '甲床淡白', '甲床青紫', '指甲干枯', '指甲反凹', '指甲薄软', '小腿青筋',
    '四肢不用', '痿废不用', '肢体瘫痪', '半身不遂', '偏瘫', '下肢水肿', '下肢微肿', '下肢浮肿',
    '四肢疼痛', '半身汗出', '四肢发凉', '肢冷', '下肢冷', '下肢发凉'];

var options19 = ['月经量多', '月经量少', '月经时多时少', '月经先期', '月经后期', '月经先后无定期',
    '闭经', '经期缩短', '经期延长', '月经紫黯', '月经淡红', '月经鲜红',
    '月经血块', '痛经', '崩漏', '停经', '经行不畅', '月经质稀', '月经质稠', '经断复来', '经来骤止',
    '月经腥臭', '经间期出血'];
var options20 = ['带下量多', '带下量少', '带下色白', '带下色黄', '带下色赤', '带下色青', '带下色黑',
    '带见五色', '带下味臭', '带下稀', '带下稠', '带下清', '带下浊', '阴痒'];
// 创建下拉多选框的函数
function createMultiSelect(options, dropdownId,x) {
    var dropdownContent = document.getElementById(dropdownId);

    // 清空之前的选项
    dropdownContent.innerHTML = '';
    let value = x.value;
    let strs = value.split(', ');
    // 创建选项并添加到下拉框
    options.forEach(function (option) {
        var label = document.createElement('label');
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.value = option;
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(option));
        dropdownContent.appendChild(label);
        if(x!=null&&x.value!=''){

            if (strs.includes(checkbox.value)) {
                checkbox.checked = true;
            }
        }
        checkbox.onclick = function () {
            toggleOption(option, dropdownId);
        };
    });
}

// 切换选项的状态（选中/取消选中）
function toggleOption(option, dropdownId) {
    var selectInput = document.getElementById('select' + dropdownId.substr(8));
    var selectedOptions = selectInput.value.trim().split(',').map(function (item) {
        return item.trim();
    });

    var index = selectedOptions.indexOf(option);
    if (index === -1) {
        selectedOptions.push(option);
    } else {
        selectedOptions.splice(index, 1);
    }
    if(selectedOptions[0]==""){
        selectedOptions.shift();
    }
    selectInput.value = selectedOptions.join(', ');
}

// 切换下拉多选框的显示/隐藏
function toggleDropdown(dropdownId) {
    var dropdownContent = document.getElementById(dropdownId);
    dropdownContent.classList.toggle('show');
}

// 初始化多个下拉多选框
function initialize() {
    createMultiSelect(options1, 'dropdown1',hanre);
    createMultiSelect(options2, 'dropdown2',hanzheng);
    createMultiSelect(options3, 'dropdown3',xingti);
    createMultiSelect(options4, 'dropdown4',shenzhi);
    createMultiSelect(options5, 'dropdown5',yinshi);
    createMultiSelect(options6, 'dropdown6',yinshui);
    createMultiSelect(options7, 'dropdown7',xiaobian);
    createMultiSelect(options8, 'dropdown8',dabian);
    createMultiSelect(options9, 'dropdown9',shuimian);
    createMultiSelect(options10, 'dropdown10',yuyin);
    createMultiSelect(options11, 'dropdown11',toumian);
    createMultiSelect(options12, 'dropdown12',toubu);
    createMultiSelect(options13, 'dropdown13',ermu);
    createMultiSelect(options14, 'dropdown14',koubiyan);
    createMultiSelect(options15, 'dropdown15',jingxiang);
    createMultiSelect(options16, 'dropdown16',xiongfu);
    createMultiSelect(options17, 'dropdown17',yaobei);
    createMultiSelect(options18, 'dropdown18',sizhi);
    createMultiSelect(options19, 'dropdown19',yuejing);
    createMultiSelect(options20, 'dropdown20',baidai);
    createMultiSelect_2(optionsZhenghou, 'dropdown21',zhenghou,inputZhenghou);
    createMultiSelect_2(optionsZhongyi, 'dropdown22',bingji,inputBingji);

    // 点击页面其他地方，关闭下拉多选框
    document.addEventListener('click', function (event) {
        var dropdowns = document.getElementsByClassName('dropdown-content');
        for (var i = 0; i < dropdowns.length; i++) {
            if (!event.target.closest('.dropdown')) {
                dropdowns[i].classList.remove('show');
            }
        }
    });
}
function createMultiSelect_2(options, dropdownId,x,show) {
    var dropdownContent = document.getElementById(dropdownId);
    // 清空之前的选项
    dropdownContent.innerHTML = '';
    // 创建选项并添加到下拉框
    let value = show.value.replace(/\s/g, '');
    let strs = value.split(',');
    let check = [];
    options.forEach(function (option) {
        var label = document.createElement('label');
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.value = option;
        checkbox.onclick = function () {
            toggleOption(option, dropdownId);
        };
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(option));
        dropdownContent.appendChild(label);
        if(show!=null&&show.value!=''){
            if (strs.includes(checkbox.value)) {
                checkbox.checked = true;
                check.push(checkbox.value);
            }
        }
    });
    let zidingyi = null;
    strs.forEach(function (i){
        if(!check.includes(i)){
            zidingyi = i;
        }
    });
    if(zidingyi==null){
        show.value='';
    }
    else {
        show.value=zidingyi;
    }
    x.value=check.join(', ');
}
//initialize();
// /22个框代码截止处

// 得到现在的时间，16位，用于biaohao
function getCurrentDateTimeString() {
    const now = new Date();

    const year = now.getFullYear().toString().padStart(4, '0');
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const milliseconds = now.getMilliseconds().toString().padStart(4, '0');

    const dateTimeString = year + month + day + hours + minutes + milliseconds;
    return dateTimeString;
}
function postData(){
    var jingyanfangxishuVal = jingyanfangXishu.value;
    if(jingyanfangxishuVal=='') {
        jingyanfangxishuVal = null;
    }
    var huanzheXingmingVal = huanzheXingming.value;
    if(huanzheXingmingVal==''){
        alert("请输入患者姓名");
        return;
    }
    var jiezhenYishengVal = jiezhenYisheng.value;
   if(jiezhenYishengVal==''){
        alert("请输入接诊医生");
        return ;
    }
    var chufuzhenVal = chufuzhen.value;
    if(chufuzhenVal==''){
        chufuzhenVal = null;
    }
    var keshiVal = keshi.value;
    if(keshiVal==''){
        keshiVal = null;
    }
    var xingbieVal = xingbie.value;
    if(xingbieVal==''){
        xingbieVal = null;
    }
    var hunkuangVal = hunkuang.value;
    if(hunkuangVal==''){
        hunkuangVal = '';
    }
    var shemaiZongtiqingkuangVal = shemaiZongtiqingkuang.value;
    if(shemaiZongtiqingkuangVal==''){
        shemaiZongtiqingkuangVal=null;
    }
    var yaowuguominshiVal = yaowuguominshi.value;
    if(yaowuguominshiVal==''){
        yaowuguominshiVal=null;
    }
    var nianVal = nian.value;
    if(nianVal==''){
        nianVal=null;
    }
    var yueVal = yue.value;
    if(yueVal==''){
        yueVal = null;
    }
    var riVal = ri.value;
    if(riVal==''){
        riVal= null;
    }
    var otherTimeVal = otherTime.value;
    if(otherTimeVal==''){
        otherTimeVal=null;
    }
    var nianlingVal = nianling.value;
    if(nianlingVal==''){
        alert("请输入年龄");
        return;
    }
    var fabingjieqiVal = fabingJieqi.value;
    if(fabingjieqiVal==''){
        fabingjieqiVal=null;
    }
    var chaodaiVal = chaodai.value;
    if(chaodaiVal==''){
        chaodaiVal=null;
    }
    var bookNameVal = bookName.value;
    if (bookNameVal == '') {
        alert("请输入书名");
        return;
    }
    var bookAuthorVal = bookAuthor.value;
    if (bookAuthorVal == '') {
        bookAuthorVal = null;
    }
    var bookPublisherVal = bookPublisher.value;
    if (bookPublisherVal == '') {
        bookPublisherVal = null;
    }
    var bookEditionVal = bookEdition.value;
    if (bookEditionVal == '') {
        bookEditionVal = null;
    }
    var bookEditionTimeVal = bookEditionTime.value;
    if (bookEditionTimeVal == '') {
        bookEditionTimeVal = null;
    }
    var bookISBNVal = bookISBN.value;
    if (bookISBNVal == '') {
        bookISBNVal = null;
    }
    var qishiyeVal = qishiye.value;
    if(qishiyeVal==''){
        alert("请输入起始页");
        return;
    }
    var zhongzhiyeVal = zhongzhiye.value;
    if(zhongzhiyeVal==''){
        alert("请输入终止页");
        return;
    }
    var zhusuVal = zhusu.value;
    if (zhusuVal == '') {
        alert("请输入主诉");
        return;
    }
    var xianbingshiVal = xianbingshi.value;
    if (xianbingshiVal == '') {
        alert("请输入现病史");
        return;
    }
    var FangFaoyuanwenVal = FangFaoyuanwen.value;
    if (FangFaoyuanwenVal == '') {
        FangFaoyuanwenVal = null;
    }
    var jiazushiVal = jiazushi.value;
    if (jiazushiVal == '') {
        jiazushiVal = null;
    }
    var jiwangshiVal = jiwangshi.value;
    if (jiwangshiVal == '') {
        jiwangshiVal = null;
    }
    var hanreVal = hanre.value;
    if (hanreVal === '') {
        hanreVal = null;
    }
    var hanzhengVal = hanzheng.value;
    if (hanzhengVal === '') {
        hanzhengVal = null;
    }
    var xingtiVal = xingti.value;
    if (xingtiVal === '') {
        xingtiVal = null;
    }
    var shenzhiVal = shenzhi.value;
    if (shenzhiVal === '') {
        shenzhiVal = null;
    }
    var yinshiVal = yinshi.value;
    if (yinshiVal === '') {
        yinshiVal = null;
    }
    var yinshuiVal = yinshui.value;
    if (yinshuiVal === '') {
        yinshuiVal = null;
    }
    var xiaobianVal = xiaobian.value;
    if (xiaobianVal === '') {
        xiaobianVal = null;
    }
    var dabianVal = dabian.value;
    if (dabianVal === '') {
        dabianVal = null;
    }
    var shuimianVal = shuimian.value;
    if (shuimianVal === '') {
        shuimianVal = null;
    }
    var yuyinVal = yuyin.value;
    if (yuyinVal === '') {
        yuyinVal = null;
    }
    var toumianVal = toumian.value;
    if (toumianVal === '') {
        toumianVal = null;
    }
    var toubuVal = toubu.value;
    if (toubuVal === '') {
        toubuVal = null;
    }
    var ermuVal = ermu.value;
    if (ermuVal === '') {
        ermuVal = null;
    }
    var koubiyanVal = koubiyan.value;
    if (koubiyanVal === '') {
        koubiyanVal = null;
    }
    var jingxiangVal = jingxiang.value;
    if (jingxiangVal === '') {
        jingxiangVal = null;
    }
    var xiongfuVal = xiongfu.value;
    if (xiongfuVal === '') {
        xiongfuVal = null;
    }
    var yaobeiVal = yaobei.value;
    if (yaobeiVal === '') {
        yaobeiVal = null;
    }
    var sizhiVal = sizhi.value;
    if (sizhiVal === '') {
        sizhiVal = null;
    }
    var yuejingVal = yuejing.value;
    if (yuejingVal === '') {
        yuejingVal = null;
    }
    var baidaiVal = baidai.value;
    if (baidaiVal === '') {
        baidaiVal = null;
    }
    var zhenghouVal = zhenghou.value;
    if (zhenghouVal === '') {
        zhenghouVal = null;
    }
    var bingjiVal = bingji.value;
    if (bingjiVal === '') {
        bingjiVal = null;
    }
    var inputZhenghouVal = inputZhenghou.value;
    if (inputZhenghouVal === '') {
        inputZhenghouVal = null;
    }
    var inputBingjiVal = inputBingji.value;
    if (inputBingjiVal === '') {
        inputBingjiVal = null;
    }
    var shiyanshijianchaVal = shiyanshiJiancha.value;
    if(shiyanshijianchaVal == ''||document.getElementById('jianShiyan').style.display=='block'){
        shiyanshijianchaVal =null;
    }
    var xiyiZhenduanVal = xiyiZhenduan.textContent;
//     if (xiyiZhenduanVal === '') {
//     xiyiZhenduanVal = null;
// }
    console.log("西医诊断"+xiyiZhenduanVal)
    var zhizeVal = zhize.value;
    if (zhizeVal === '') {
        zhizeVal = null;
    }
    var zhifaVal = zhifa.value;
    if (zhifaVal === '') {
        zhifaVal = null;
    }
    var shuomingVal = shuoming.value;
    if (shuomingVal === '') {
        shuomingVal = null;
    }
    var qitaYizhuVal = qitaYizhu.value;
    if (qitaYizhuVal === '') {
        qitaYizhuVal = null;
    }
    var yaohoufankuiVal = yaohoufankui.value;
    if (yaohoufankuiVal === '') {
        yaohoufankuiVal = null;
    }
    var yaodianVal = yaodian.value;
    if (yaodianVal === '') {
        alert("请输入病案评论及要点");
        return;
    }
    var chufangming_JVal = chufangming_J.value;
    if (chufangming_JVal === '') {
        chufangming_JVal = null;
    }
    var jishu_JVal = jishu_J.value;
    if (jishu_JVal === '') {
        jishu_JVal = null;
    }
    var jianfufa_JVal = jianfufa_J.value;
    if (jianfufa_JVal === '') {
        jianfufa_JVal = null;
    }
    var chufangming_XVal = chufangming_X.value;
    if (chufangming_XVal === '') {
        chufangming_XVal = null;
    }
    var leixing_XVal = leixing_X.value;
    if (leixing_XVal === ''||xiangban.style.display=='none') {
        leixing_XVal = null;
    }
    var jixing_XVal = jixing_X.value;
    if (jixing_XVal === ''||xiangban.style.display=='none') {
        jixing_XVal = null;
    }
    var jianfufa_XVal = jianfufa_X.value;
    if (jianfufa_XVal === '') {
        jianfufa_XVal = null;
    }
    var fuyaoshijian_XVal = fuyaoshijian_X.value;
    if (fuyaoshijian_XVal === ''||xiangban.style.display=='none') {
        fuyaoshijian_XVal = null;
    }
    var jishu_XVal = jishu_X.value;
    if (jishu_XVal === '') {
        jishu_XVal = null;
    }
    var shiyongfangfa_XVal = shiyongfangfa_X.value;
    if (shiyongfangfa_XVal === ''||xiangban.style.display=='none') {
        shiyongfangfa_XVal = null;
    }
    var cishuyaoliang_XVal = cishuyaoliang_X.value;
    if (cishuyaoliang_XVal === ''||xiangban.style.display=='none') {
        cishuyaoliang_XVal = null;
    }
    var fuhoufankui_XVal = fuhoufankui_X.value;
    if (fuhoufankui_XVal === ''||xiangban.style.display=='none') {
        fuhoufankui_XVal = null;
    }
    var qitashixiang_XVal = qitashixiang_X.value;
    if (qitashixiang_XVal === ''||xiangban.style.display=='none') {
        qitashixiang_XVal = null;
    }
    var jinguzhiVal;
    if (xiangban.style.display=='none') {
        jinguzhiVal = null;
    }
    else if(jinguzhiJin_X.checked){
        jinguzhiVal = '今制';
    }
    else {
        jinguzhiVal = '古制';
    }
    var daiding_XVal = daiding_X.value;
    if (daiding_XVal === ''||xiangban.style.display=='none') {
        daiding_XVal = null;
    }
    var chufangming,jishu,jianfufa;
    if(xiangban.style.display=='none'){
        chufangming = chufangming_JVal;
        jishu = jishu_JVal;
        jianfufa = jianfufa_JVal;
    }
    else {
        chufangming = chufangming_XVal;
        jishu = jishu_XVal;
        jianfufa = jianfufa_XVal;
    }

    // 创建要发送的数据对象，不包括文件
    var yianData = {
        id: yianId.value,
        experienceCoefficient:jingyanfangxishuVal,
        xingming: huanzheXingmingVal,
        jiuzhenyisheng: jiezhenYishengVal,
        jiuzhenleixin: chufuzhenVal,
        keshi: keshiVal,
        xingbie: xingbieVal,
        hunkuang: hunkuangVal,
        yaowoguominshi: yaowuguominshiVal,
        year: nianVal,
        month: yueVal,
        day: riVal,
        otherTime: otherTimeVal,
        nianling: nianlingVal,
        fabingjieqi: fabingjieqiVal,
        chaodai: chaodaiVal,
        shuming: bookNameVal,
        isbn:bookISBNVal,
        yema: qishiyeVal,
        yemaEnd: zhongzhiyeVal,
        banci: bookEditionVal,
        chubanshijian: bookEditionTimeVal,
        zuozhe: bookAuthorVal,
        chubanshe: bookPublisherVal,
        zhushu: zhusuVal,
        xianbingshi: xianbingshiVal,
        fangFaoyuanwen: FangFaoyuanwenVal,
        shezhen: shemaiZongtiqingkuangVal,
        jzs: jiazushiVal,
        jws: jiwangshiVal,
        hanre: hanreVal,
        hanzhen: hanzhengVal,
        xingti: xingtiVal,
        shenzhi: shenzhiVal,
        yinshi: yinshiVal,
        yinshui: yinshuiVal,
        xiaobian: xiaobianVal,
        dabian: dabianVal,
        shuimian: shuimianVal,
        yuyan: yuyinVal,
        toumian: toumianVal,
        toubu: toubuVal,
        ermu: ermuVal,
        koubiyan: koubiyanVal,
        jingxiang: jingxiangVal,
        xiongfu: xiongfuVal,
        yaobei: yaobeiVal,
        sizhi: sizhiVal,
        yuejing: yuejingVal,
        baidai: baidaiVal,
        sysjc: shiyanshijianchaVal,
        zhize: zhizeVal,
        zhifa: zhifaVal,
        shuoming: shuomingVal,
        qtyz: qitaYizhuVal,
        bafx: yaohoufankuiVal,
        xxxd: yaodianVal,
        chufangmingcheng: chufangming,
        leixing: leixing_XVal,
        jixing: jixing_XVal,
        jianfufa: jianfufa,
        fuyaoshijian: fuyaoshijian_XVal,
        jishu: jishu,
        shiyongfangfa: shiyongfangfa_XVal,
        cishuyaoliang: cishuyaoliang_XVal,
        fuhoufankui: fuhoufankui_XVal,
        qitashixiang: qitashixiang_XVal,
        jinguzhi: jinguzhiVal
    };
    she();
    mai();
    if(document.getElementById('xiyijianchabiao').style.display=='block') {
        jiancha();
        shiyanshijianchaVal=null;
    }
    else{
        jianchaData=null;
        jcTupian=null;
    }

    var formData =new FormData();
    formData.append('yian',JSON.stringify(yianData));  //医案
    formData.append('she',JSON.stringify(sheData));  //舌
    formData.append('mai',JSON.stringify(maiData));  //脉
    formData.append('zhenghou',inputZhenghouVal+','+zhenghouVal);  //症状或症候
    formData.append('bingji',inputBingjiVal+','+bingjiVal);   //中医
    formData.append('zhenduan',xiyiZhenduanVal);   //西医诊断
    formData.append('jiancha',JSON.stringify(jianchaData));   //西医检查数据详细
    if(jcTupian==null){
        formData.append('fileArray', null);  //西医检查
    }
    else {
        for (var i = 0; i < jcTupian.length; i++) {
            if(jcTupian[i]==null){
                formData.append('fileArray', new Blob());  //空对象占位
            }
            else {
                formData.append('fileArray', jcTupian[i]);  //西医检查
            }
        }
    }
    if(jianban.style.display!='none'){
        formData.append('yao',JSON.stringify(data_J));  //处方
    }
    else {
        formData.append('yao',JSON.stringify(data_X));  //处方
    }
    formData.append('imageCover',fengmian.files[0]);
    formData.append('imageRight',banquanye.files[0]);
    for (var k = 0; k < cankao.length; k++) {
        formData.append('cankaoFiles', cankao[k]);  //参考图片
    }
    // 发送 POST 请求
    fetch('/wxya/', {
        method: 'PUT',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            alert("保存成功！");
            console.log("发送成功");
        })
        .catch(error => {
            alert("保存成功！");
            console.log(error);
        });
}
preloadJcTupian();
function preloadJcTupian(){
    const table = document.getElementById('tupianPre');
    const rows = table.querySelectorAll('tbody tr');
    rows.forEach(function (row, index) {
        const img = row.querySelector('td:first-child img');
        const fileName = row.querySelector('td:nth-child(2)').textContent;
        const imgSrc = img.getAttribute('src');
        console.log(fileName+'     '+imgSrc);
        if (imgSrc=='/loadImages/') {
            jcTupian.push(null);
        }
        else{
            let base64 = getBase64(img);
            jcTupian.push(base64ToFile(base64,getFileExtension(fileName)));
        }

    });
}
function she() {
    // 获取表格元素
    var table = document.getElementById('resultTable');
    // 获取所有的<tr>元素
    var rows = table.querySelectorAll('tr');
    // 从第二行开始遍历每个<tr>元素，获取第二列和第三列的值
    for (var i = 1; i < rows.length; i++) {
        var row = rows[i];
        var columns = row.querySelectorAll('td');
        var typeValue = columns[1].textContent;
        var valueValue = columns[2].textContent;
        // 创建一个包含typeValue和valueValue的对象
        var dataObject = {
            type: typeValue,
            value: valueValue
        };
        // 将对象添加到dataArray数组中
        sheData.push(dataObject);
    }

}
function mai() {
    // 获取表格元素
    var table = document.getElementById('resultTable_2');
    // 获取表格的所有行
    var rows = table.getElementsByTagName('tr');
    // 从第一行开始遍历每一行，获取第二列的值
    for (var i = 1; i < rows.length; i++) {
        var row = rows[i];
        var columns = row.getElementsByTagName('td');
        var contentValue = columns[1].textContent.replace(/[\n\s]/g, '');
        // 将contentValue添加到数组中
        maiData.push(contentValue);
    }
    console.log("mai      "+maiData)
}
function jiancha() {
    // 获取表格元素
    var table = document.getElementById('divJiancha');
    var rows = table.getElementsByTagName('tr');

    for (var i = 1; i < rows.length; i++) {
        var row = rows[i];
        var columns = row.getElementsByTagName('td');
        // 获取第二列、第三列、第四列的值
        var column2Value = columns[1].textContent;
        var column3Value = columns[2].textContent;
        var column4Value = columns[3].textContent;
        if(column3Value==''){
            column3Value=null;
        }
        if(column4Value==''){
            column4Value=null;
        }
        // 创建一个对象，存储当前行的数据
        var rowData = {
            jianchaxiangmu: column2Value,
            shijian: column3Value,
            jieguo: column4Value
        };
        jianchaData.push(rowData);
    }
}
changeStatus();
function changeStatus(){
    let nowValue = shenhe.innerText;
    const role = document.getElementById('Userrole').textContent;
    if(nowValue=='保存'){
        document.getElementById('ysBtn').style.display='inline-block';
        document.getElementById('tjShow').style.display='inline-block';
        document.getElementById('starTable').style.display='block';
    }
    else if(nowValue=='一审'){
        document.getElementById('esBtn').style.display='inline-block';
        document.getElementById('ysShow').style.display='inline-block';
        document.getElementById('starTable').style.display='block';
    }
    else{
        if(role=='管理员')   document.getElementById('esShow').style.display='inline-block';
        else{
            document.getElementById('saveButton').style.display = 'none';
            document.getElementById('esShow').style.display='inline-block';
        }

        return;
    }
    if(role=='学生'){
        if(nowValue == '一审'){
            document.getElementById('saveButton').style.display = 'none';
            document.getElementById('ysBtn').style.display='none';
            document.getElementById('tjShow').style.display='none';
            document.getElementById('starTable').style.display='none';
            document.getElementById('esBtn').style.display='none';
            document.getElementById('esShow').style.display='none';
        }
        else{
            document.getElementById('saveButton').style.display = 'inline-block';
            document.getElementById('tjShow').style.display='inline-block';
            document.getElementById('ysBtn').style.display='none';
            document.getElementById('starTable').style.display='none';
            document.getElementById('esBtn').style.display='none';
            document.getElementById('ysShow').style.display='none';
            document.getElementById('esShow').style.display='none';
        }
    }
    else if((role=='二级审核'||role=='教师审核'||role=='名医专家')&&nowValue!='保存'){
        document.getElementById('saveButton').style.display = 'none';
        document.getElementById('ysBtn').style.display='none';
        document.getElementById('starTable').style.display='none';
        document.getElementById('esBtn').style.display='none';
    }

}

// 将图片转base64编码，传参为img标签
function getBase64(img){
// 创建一个Canvas元素
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
// 将图片绘制到Canvas上
    canvas.width = img.width;
    canvas.height = img.height;
    context.drawImage(img, 0, 0, img.width, img.height);
// 获取Base64编码的数据URL

// base64Image 就是图片的Base64编码的数据URL
    return canvas.toDataURL('image/png');// 可以根据图片类型调整参数
}
// base64转file，传参为base64和后缀名
function base64ToFile(dataurl,filename){
    if(dataurl==null||dataurl==undefined){
        return ;
    }
    var arr = dataurl.split(',');
    var mimeTemp = arr[0].match(/:(.*?);/)
    if(mimeTemp == null ){
        return
    }
    var mime = mimeTemp[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}
//下面是上传参考图片的代码
const imgsInput = document.getElementById('imgsInput');
const fileListElement = document.getElementById('fileList');
const previewContainer = document.getElementById('previewContainer');
const previewImage = document.getElementById('previewImage');

imgsInput.addEventListener('change', updateFileList);

function updateFileList() {
    const files = imgsInput.files;
    for (let i = 0; i < files.length; i++) {
        const fileName = files[i].name;
        cankao.push(files[i]); // 将文件添加到数组中

        const row = document.createElement('tr');
        const nameCell = document.createElement('td');
        const deleteCell = document.createElement('td');
        const previewCell = document.createElement('td');

        nameCell.textContent = fileName;
        row.appendChild(nameCell);

        const deleteLink = document.createElement('a');
        deleteLink.textContent = '删除';
        deleteLink.href = '#'; // 设置为 '#'，防止页面跳转
        deleteLink.addEventListener('click', () => deleteRowAndFile(i, row));
        deleteCell.appendChild(deleteLink);
        row.appendChild(deleteCell);

        const previewLink = document.createElement('a');
        previewLink.textContent = '预览';
        previewLink.href = '#'; // 设置为 '#'，防止页面跳转
        previewLink.addEventListener('click', () => showPreview(files[i]));
        previewCell.appendChild(previewLink);
        row.appendChild(previewCell);

        fileListElement.appendChild(row);
    }
}

function deleteRowAndFile(index, row) {
    cankao.splice(index, 1); // 删除数组中的对应文件名
    fileListElement.removeChild(row); // 删除表格中的对应行
}

function showPreview(file) {
    previewImage.src = URL.createObjectURL(file);
    previewContainer.style.display = 'block';
}

function closePreview() {
    previewImage.src = '';
    previewContainer.style.display = 'none';
}
preloadCankao();
function preloadCankao(){
    const table = document.querySelector('.cankaoTable');
    const rows = table.querySelectorAll('tbody tr');

    rows.forEach(function (row, index) {
        if (index > 0) { // Skip the first row
            const fileName = row.querySelector('td:first-child').textContent;
            const secondColumnLink = row.querySelector('td:nth-child(2) a');
            const thirdColumnLink = row.querySelector('td:nth-child(3) a');
            const img = row.querySelector('td:nth-child(4) img');
            const imgSrc = img.getAttribute('src');
            if (secondColumnLink) {
                secondColumnLink.addEventListener('click', () => deleteRowAndFile(index, row));
            }
            if (thirdColumnLink) {
                thirdColumnLink.addEventListener('click', () => showPreview_load(imgSrc));
            }
            if (img) {
                let base64 = getBase64(img);
                cankao.push(base64ToFile(base64,fileName)); //测试
            }
        }
    });
}
function getFileExtension(fileName) {
    const lastDotIndex = fileName.lastIndexOf(".");
    if (lastDotIndex > 0 && lastDotIndex < fileName.length - 1) {
        return fileName.substring(lastDotIndex + 1);
    }
    return "";
}


function showPreview_load(file) {
    previewImage.src = file;
    previewContainer.style.display = 'block';
}
preloadChufang();
function preloadChufang(){
    let jianCheck = true;
    // 获取表格元素
    const table = document.getElementById('chufang_');
    if(table.rows.length==0) {
        return;
    }
    // 遍历每一行
    for (let i = 0; i < table.rows.length; i++) {
        const row = table.rows[i];
        const columns = row.cells;
        // 获取每一列的内容
        const zhongyaoming = columns[0].textContent;
        const yaoliang = columns[1].textContent;
        const daiding = columns[2].textContent;
        const paozhi = columns[3].textContent;
        const chandi = columns[4].textContent;
        const beizhu = columns[5].textContent;
        var sort = 0;
        if (data_J.length > 0) {
            sort = data_J[data_J.length - 1].sort+1;
        }
        if(daiding!=null&&daiding!=''){
            jianCheck = false;
            data_X[cnt_X]={
                zhongyao:zhongyaoming,
                yaoliang:yaoliang,
                beizhu:beizhu,
                paozhi:paozhi,
                chandi:chandi,
                daiding:daiding,
                sort:sort
            }
            cnt_X++;
        }
        else{
            data_J[cnt_J]={
                zhongyao:zhongyaoming,
                yaoliang:yaoliang,
                beizhu:beizhu,
                paozhi:null,
                chandi:null,
                daiding:null,
                sort:sort
            }
            cnt_J++;
        }
    }
    if(jianCheck){
        addCf_J_Show();
    }
    else {
        addCf_X_Show();
    }
}
